package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashSet;


@Service
public class UploadService {
    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);
    @Autowired
    private FastFileStorageClient storageClient;

    public String uploadImage(MultipartFile file) {

        try {
            // 1. 校验文件的媒体类型
            HashSet<String> hashSet = new HashSet<>();
            hashSet.add("image/jpeg");
            hashSet.add("image/png");
            String type = file.getContentType();
            boolean result = hashSet.contains(type);
            if (!result) {
                logger.info("上传的文件类型不匹配,不是image文件");
                return null;
            }
            //2. 校验文件的内容,判断是不是一个图片文件
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                logger.info("上传失败，文件内容不符合要求");
                return null;
            }
            //3.保存图片到本地
           /* File dir = new File("G:/tupian");
            if (!dir.exists()) {  //如果目录不存在则创建
                dir.mkdirs();
            }
            String filename = file.getOriginalFilename();
            file.transferTo(new File(dir, filename));
            String url = "http://127.0.0.1:8082/upload/img/" + filename;*/

            //上传图片到fastDfs服务器
            //获取文件后缀名
            String suffix = StringUtils.substringAfterLast(file.getOriginalFilename(), ".");
            //上传图片
            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), suffix, null);
            return "http://image.leyou.com/" + storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


    }
}
